package com.example.lj.uav.sqlite;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SQLiteDbHelper extends SQLiteOpenHelper {

    private static final String DB_NAME = "record.db";

    private static final int DB_VERSION = 1;

    private static final String TABLE_NAME = "flightrecorder";

    //创建 students 表的 sql 语句
    private static final String STUDENTS_CREATE_TABLE_SQL = "create table " + TABLE_NAME + "("
            + "id integer primary key autoincrement,"
            + "_date varchar(30) not null,"
            + "_time INTEGER DEFAULT 0,"
            + "_distance INTEGER DEFAULT 0,"
            + "_height FLOAT DEFAULT 0.0,"
            + "_speed FLOAT DEFAULT 0.0,"
            + "_takeoff FLOAT DEFAULT 0.0"
            + ");";

    public SQLiteDbHelper(Context context) {
        super(context, DB_NAME, null, DB_VERSION);
    }


    @Override
    public void onCreate(SQLiteDatabase db) {
        db.execSQL(STUDENTS_CREATE_TABLE_SQL);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {

    }

    public void dbInsert(ContentValues contentValues) {
        SQLiteDatabase wdb = getWritableDatabase();
        wdb.insert(TABLE_NAME, null, contentValues);
        wdb.close();
    }

    public List<Map<String, Object>> dbQuery() {
        return dbQuery("", new String[]{});
    }

    public List<Map<String, Object>> dbQuery(String selection, String[] zw) {
        SQLiteDatabase wdb = getWritableDatabase();
        // 相当于 select * from  语句
        Cursor cursor = wdb.query(TABLE_NAME,
                null,
                selection,
                zw,
                null,
                null,
                null,
                null);
        List<Map<String, Object>> list = new ArrayList<>();
        while (cursor.moveToNext()) {
            HashMap<String, Object> map = new HashMap<>();
            map.put("date", cursor.getString(cursor.getColumnIndex("_date")));
            map.put("time", cursor.getInt(cursor.getColumnIndex("_time")));
            map.put("distance", cursor.getInt(cursor.getColumnIndex("_distance")));
            map.put("height", cursor.getFloat(cursor.getColumnIndex("_height")));
            map.put("speed", cursor.getFloat(cursor.getColumnIndex("_speed")));
            map.put("takeoff", cursor.getFloat(cursor.getColumnIndex("_takeoff")));
            list.add(map);
        }
        cursor.close();
        return list;
    }
}
